import Vue from 'vue'
import Vuex from 'vuex'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'
import {
	getLocation,
	setLocation,
	removeLocation
} from '@/utils/location.js'
import {
	login,
	logout,
	getUserInfo,
	updateUserInfo
} from '@/api/user'

Vue.use(Vuex)

const getDefaultState = () => {
	return {
		token: getToken(),
		name: '', //用户名称
		avatar: '', //用户头像
		phoneNumber: '', //用户手机号码
		location: getLocation()
	}
}
const state = getDefaultState()

const mutations = {
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	SET_PHONENUMBER: (state, phoneNumber) => {
		state.phoneNumber = phoneNumber
	},
	SET_LOCATION: (state, location) => {
		state.location = location
	}
}

const actions = {
	// 手机号码|用户名|邮箱 + 密码登录方式 
	login({
		commit
	}, userInfo) {
		const {
			code,
			codeMobile,
			encryptedData,
			iv,
			inviteCode
		} = userInfo
		return new Promise((resolve, reject) => {
			login({
				code,
				codeMobile,
				encryptedData,
				iv,
				inviteCode
			}).then(response => {
				const {
					token
				} = response

				commit('SET_TOKEN', token)
				setToken(token)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	getUserInfo({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			getUserInfo(state.token).then(response => {
				if (!response) {
					reject('用户信息不能为空')
				}

				const {
					nickname,
					avatar,
					phoneNumber
				} = response

				commit('SET_NAME', nickname)
				commit('SET_AVATAR', avatar)
				commit('SET_PHONENUMBER', phoneNumber)
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	updateUserInfo({
		commit,
		state
	}, userInfo) {
		return new Promise((resolve, reject) => {
			updateUserInfo({
				avatar: userInfo.avatarUrl,
				nickname: userInfo.nickName
			}).then(response => {
				commit('SET_NAME', userInfo.nickName)
				commit('SET_AVATAR', userInfo.avatarUrl)
				resolve(response)
			}).catch(error => {
				reject(error)
			})
		})
	},
	logout({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			logout(state.token).then(() => {
				removeToken() // must remove  token  first
				commit('RESET_STATE')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	resetToken({
		commit
	}) {
		return new Promise(resolve => {
			removeToken() // must remove  token  first
			commit('RESET_STATE')
			resolve()
		})
	},
	updateLocation({
		state,
		commit
	}, location) {
		return new Promise(resolve => {
			setLocation(location)
			commit('SET_LOCATION', location)
			resolve()
		})
	}
}

const store = new Vuex.Store({
	state,
	mutations,
	actions
})

export default store